<template>
  <div>
    <div class="search-title">查询条件</div>
    <div class="search-box">
      <a-form-model :model="searchForm" layout="inline" ref="searchForm" class="searchForm">
        <a-form-model-item label="课程标题" prop="courseTitle">
          <a-input v-model="searchForm.courseTitle" placeholder="请输入课程标题" />
        </a-form-model-item>
        <a-form-model-item label="课程类型" prop="courseType">
          <a-select v-model="searchForm.courseType" placeholder="请选择课程类型">
            <a-select-option v-for="item in courseTypeDict" :key="item.value" :value="item.value">
              {{ item.text }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item class="searchButton">
          <a-button type="primary" v-if="QX.read" @click="getSearch">查询</a-button>
          <a-button type="default" v-if="QX.read" @click="restSearch('searchForm')">重置</a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="table-operation">
      <a-button type="primary" icon="plus" v-if="QX.add" @click="openDrawer">新增课程</a-button>
    </div>
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="false"
      :loading="loading"
      rowKey="courseId"
      :scroll="{ y: this.$getViewportSize().height - 300 }">
      <span slot="images" slot-scope="text, record">
        <img :src="fullImageUrlList(record.coverImage)" @click="showImage(record.coverImage)"   alt="封面图片" style="width: 25px; height: 25px;"  />
      </span>
      <span slot="action" slot-scope="text, record">
        <a @click="editCourse(record)" v-if="QX.edit"><a-icon class="iconBtn" type="edit" />编辑</a>
        <a-divider v-if="QX.edit && QX.delete" type="vertical" />
        <a-popconfirm title="确认是否删除？" ok-text="是" cancel-text="否" @confirm="removeCourse(record)">
          <a v-if="QX.delete"><a-icon class="iconBtn" type="delete" />删除</a>
        </a-popconfirm>
      </span>
    </a-table>
    <a-pagination
      show-size-changer
      :total="total"
      :current="pageIndex"
      :pageSize="pageSize"
      @showSizeChange="onShowSizeChange"
      @change="onChangePage"
      style="float: right; margin-top: 15px"
    />
    <a-drawer
      :closable="true"
      :title="drawerTitle"
      :visible="visible"
      @close="visible=!visible"
      :width="550">
      <a-spin class="submitLoading" :spinning="submitLoading">
        <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules" ref="form" >
          <a-form-model-item label="课程标题" prop="courseTitle">
            <a-input v-model="form.courseTitle" placeholder="请输入课程标题" />
          </a-form-model-item>
          <a-form-model-item label="封面图片" prop="cover">
            <a-upload
              :before-upload="beforeCoverUpload"
              :file-list="coverList"
              @change="handleCoverRemove">
              <a-button>选择封面</a-button>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item label="课程简介" prop="introduction">
            <a-textarea v-model="form.introduction" rows="3" placeholder="请输入课程简介" />
          </a-form-model-item>
          <a-form-model-item label="最低时长" prop="minStudyTime">
            <a-input-number  v-model="form.minStudyTime" :min="0" />
          </a-form-model-item>
          <a-form-model-item label="课程类型" prop="courseType">
            <a-select v-model="form.courseType" placeholder="请选择课程类型">
              <a-select-option v-for="item in courseTypeDict" :key="item.value" :value="item.value">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="课程文件" prop="file">
            <a-upload
              :before-upload="beforeFileUpload"
              :file-list="fileList"
              @change="handleFileRemove">
              <a-button>选择文件</a-button>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item label="关联岗位" prop="positionId">
            <a-select
              v-model="form.positionId"
              placeholder="请选择关联岗位"
              mode="multiple"
              :token-separators="[]"
            >
            <a-select-option v-for="item in positionDict" :key="item.value" :value="item.value">
              {{ item.text }}
            </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
        <div
          :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '8px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
          <a-button
            type="default"
            @click="visible=!visible"
          >
            取消
          </a-button>
          <a-button
            type="primary"
            @click="submitForm"
          >
            确认
          </a-button>
        </div>
      </a-spin>
    </a-drawer>
    <a-modal
      v-model:visible="isModalVisible"
      title="放大图片"
      @cancel="closeModal"

    >
      <img
        :src="fullImageUrl1"
        alt="放大图片"
        style="width: 100%; height: auto;"
      />
    </a-modal>
  </div>
</template>

<script>
import {req} from '../../api/axiosFun'
import TableTootip from '../../components/TableTootip.vue'
import preventBack from 'vue-prevent-browser-back'
import axios from "axios";
export default {
  name: 'Course',
  mixins: [preventBack],
  components:{
    TableTootip
  },
  data() {
    return {
      QX: {},
      visible: false,
      submitLoading: false,
      drawerTitle:"课程信息",
      form: {
        courseId: 0,
        courseTitle: '',
        coverImage: '',
        introduction: '',
        minStudyTime: 0,
        courseType: '',
        coursePath: '',
        positionId: [],
        cover:'',
        file:'',
      },
      rules: {
        courseTitle: [{ required: true, message: '请输入课程标题', trigger: 'blur' }],
        introduction: [{ required: true, message: '请输入课程介绍', trigger: 'blur' }],
        courseType: [{ required: true, message: '请选择课程类型', trigger: 'blur' }],
        positionId: [{ required: true, message: '请选择关联岗位', trigger: 'blur' }],
        minStudyTime: [{ required: true, message: '请输入课程介绍', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (isNaN(Number(value))) {
                callback(new Error('请输入有效的数字'));
              } else if (Number(value) <= 0) {
                callback(new Error('请输入大于 0 的数字'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        cover: [ // 自定义一个 cover 字段用于校验
          {
            validator: (rule, value, callback) => {
              if (this.coverList.length === 0) {
                callback(new Error('请上传封面图片'));
              } else {
                callback();
              }
            },
            trigger: 'blur' //
          }
        ],
        file: [ // 自定义一个 cover 字段用于校验
          {
            validator: (rule, value, callback) => {
              if (this.fileList.length === 0) {
                callback(new Error('请上传课程文件'));
              } else {
                callback();
              }
            },
            trigger: 'blur' //
          }
        ]
      },
      searchForm: { courseTitle: '', courseType: '' },
      dataList: [],
      columns: [],
      courseTypeDict: [],
      positionDict: [],
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      coverList: [],
      fileList: [],
      isModalVisible: false,
      fullImageUrl1:''
    }
  },
  mounted() {

    this.getCourseList()
    this.loadDicts()

  },
  methods: {
    // 处理文件删除事件
    handleRemove(file) {
      console.log('删除文件:', file);
      // 更新 fileList，移除被删除的文件
      this.fileList = this.fileList.filter(item => item.uid !== file.uid);
      // 返回 true 表示确认删除
      return true;
    },
    // 处理封面删除
    handleCoverRemove(info) {
      if (info.file.status === 'removed') {
        console.log('handleCoverRemove');
        this.coverList = []; // 清空封面列表
        this.form.coverImage = ''; // 清空表单中的封面图片字段
      }
    },

    // 处理文件删除
    handleFileRemove(info) {
      console.log('文件变化:', info);

      // 处理删除操作
      if (info.file.status === 'removed') {
        this.fileList = []; // 清空文件列表
        this.form.coursePath = ''; // 清空表单中的课程文件路径
      }

    },
    loadDicts() {
      req('get', '/dict/get/course_type').then(res => { this.courseTypeDict = res.data })
      req('get', '/dict/get/position').then(res => { this.positionDict = res.data })
    },
    fullImageUrl(){
      return `${process.env.API}/${this.form.coverImage}`;
    },
    fullImageUrlList(image){
      return `${process.env.API}/`+image;
    },
    fullDataUrl(){
      return `${process.env.API}/${this.form.coursePath}`;
    },
    getSearch() { this.pageIndex = 1; this.getCourseList() },
    restSearch(form) { this.$refs[form].resetFields(); this.pageIndex = 1; this.getCourseList() },
    getCourseList() {
      this.loading = true
      this.searchForm.page = this.pageIndex
      this.searchForm.rows = this.pageSize
      req('post', '/course/selectBCourse1listPage', this.searchForm)
        .then(res => {
          this.loading = false
          if (res.result === 'success') {
            this.dataList = res.data
            this.QX = res.QX
            this.total = res.page.totalResult
            this.initColumns()
          }
        }).catch(() => { this.loading = false })
    },
    initColumns() {
      this.columns = [
        { title: '序号', width: '50px', align: 'center', customRender: (text, row, index) => index + 1 , width: 50},
        { title: '课程标题', dataIndex: 'courseTitle', key: 'courseTitle', align: 'center' },
        { title: '封面图片', dataIndex: 'coverImage', key: 'images', align: 'center', scopedSlots: { customRender: 'images' } , width: 100},
        {
          title: '课程简介',
          dataIndex: 'introduction',
          key: 'introduction',
          align: 'center',
          // 添加自定义渲染
          customRender: (text) => {
            if (!text) return '';
            // 超过8字符显示省略号
            return text.length > 8 ?
              <a-tooltip title={text}>{text.substring(0, 8)}...</a-tooltip> :
              text;
          },
        },
        { title: '最低学习时间', dataIndex: 'minStudyTime', key: 'minStudyTime', align: 'center', width: 100 },
        { title: '课程类型', dataIndex: 'courseTypeName', key: 'courseTypeName', align: 'center' },
        // { title: '课程文件路径', dataIndex: 'coursePath', key: 'coursePath', align: 'center' },
        {
          title: '关联岗位',
          dataIndex: 'positionName',
          key: 'positionName',
          align: 'center',
          // 添加自定义渲染
          customRender: (text) => {
            if (!text) return '';
            // 超过8字符显示省略号
            return text.length > 10 ?
              <a-tooltip title={text}>{text.substring(0, 10)}...</a-tooltip> :
              text;
          },
        },
        { title: '创建时间', dataIndex: 'createDatetime', align:'center', key: 'createDatetime', scopedSlots: { customRender: 'createDatetime' }, width: 200},
      ]
      const actionCol = {
        title: '操作', key: 'action', align: 'center', scopedSlots: { customRender: 'action' }
      }
      if ((this.QX.edit || this.QX.delete)) {
        this.columns.push(actionCol)
      }
    },
    openDrawer() {
      this.visible = true
      this.form.courseId = 0
      this.clearFiles()
    },
    editCourse(record) {
      this.loading = true
      req('post', '/course/getBCourseById', { courseId: record.courseId }).then(res => {
        this.loading = false
        if (res.result === 'success') {
          this.visible = true
          this.form = { ...res.data }
          // 将逗号分隔的字符串转为数组
          this.form.positionId = res.data.positionId
            ? res.data.positionId.split(',')
            : [];

          // 初始化封面（仅显示，不上传）
          this.coverList = res.data.coverImage ? [{
            uid: '1',
            name: '封面图片.jpg',
            status: 'done',
            url: this.fullImageUrl(),
            isExisting: true // 标记为已有文件
          }] : [];

          // 初始化课程文件（仅显示，不上传）
          this.fileList = res.data.coursePath ? [{
            uid: '2',
            name: '课程文件',
            status: 'done',
            url: this.fullDataUrl(),
            isExisting: true // 标记为已有文件
          }] : [];
        }
      })
    },
    beforeCoverUpload(file) {

      this.coverList.length = 0;
      this.coverList = [...this.coverList, file];
      return false;
    },
    beforeFileUpload(file) {
      this.fileList.length = 0;
      this.fileList = [...this.fileList, file];
      return false;
    },
    clearFiles() {
      this.coverList = []
      this.fileList = []
      this.form = { courseId: 0, courseTitle: '', coverImage: '', introduction: '', minStudyTime: 0, courseType: '', coursePath: '', positionId: [] }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          const { fileList,coverList } = this;
          const formData = new FormData();
          for (var key in this.form) {
            formData.append(key, this.form[key]||'');
          }
          // 将数组转为逗号分隔的字符串
          if (Array.isArray(this.form.positionId)) {
            formData.append('positionId', this.form.positionId.join(','));
          }
          fileList.forEach(file => {
            formData.append('courseFile', file);
          });
          coverList.forEach(file => {
            formData.append('coverImage', file);
          });
          const url = this.form.courseId ? '/course/edit' : '/course/add';
          axios(
            {
              method: 'post',
              url: url,
              headers: {
                'Access-Token': localStorage.getItem('token')
              },
              data: formData
            })
            .then((response) => {
              this.submitLoading = false
              if (response.data.result === 'success') {
                this.fileList = [];
                this.coverList = [];
                this.visible = false;
                this.getCourseList();
                this.form.fileStatus = '0';
                this.$message.success(response.data.message);
              } else {
                if (response.data.fileStatus == 1) {
                  this.visibleSub = true;
                } else if (response.data.result === 'failed') {
                  this.$message.warning(response.data.message);
                } else {
                  this.$message.error(response.data.message);
                }
              }
            })
            .catch(error => {
              if (error.response.status === 403) {
                //没权限
                this.$message.warning(error.response.data.message);
              } else {
                this.$message.error(error.response.data.message);
              }
              this.uploading = false;
            });
        }
      });
    },
    removeCourse(record) {
      this.loading = true
      req('post', '/course/removeBCourse', { courseId: record.courseId }).then(res => {
        this.loading = false
        if (res.result === 'success') {
          this.$message.success(res.message)
          this.getCourseList()
        }
      })
    },
    onChangePage(page) { this.pageIndex = page; this.getCourseList() },
    onShowSizeChange(current, size) { this.pageIndex = 1; this.pageSize = size; this.getCourseList() },
    closeModal() {
      this.isModalVisible = false;
    },
    showImage(relativePath) {
      this.fullImageUrl1 = this.fullImageUrlList(relativePath);
      this.isModalVisible = true;
    },
    openDrawer() {
      this.visible = true
      this.form.courseId = 0
      this.clearFiles();
      this.$refs.form.resetFields();
    },
  }
}
</script>

<style scoped>
@import "../../assets/css/maincss.css";
</style>
